<template>
  <div class="container mx-auto px-4 py-8 mt-16">
    <div class="max-w-4xl mx-auto">
      <div class="flex items-center justify-between mb-8">
        <h1 class="text-2xl font-bold">{{ isEdit ? '编辑文章' : '写文章' }}</h1>
      </div>

      <div class="space-y-6">
        <!-- 标题输入 -->
        <div class="space-y-2">
          <label class="text-sm font-medium">文章标题</label>
          <input
            v-model="articleForm.articleTitle"
            type="text"
            placeholder="请输入文章标题"
            class="w-full px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
          />
        </div>

        <!-- 分类选择 -->
        <div class="space-y-2">
          <label class="text-sm font-medium">文章分类</label>
          <select
            v-model="articleForm.categoryId"
            class="w-full px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
          >
            <option value="0">请选择分类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.categoryName }}
            </option>
          </select>
        </div>

        <!-- 文章类型 -->
        <div class="space-y-2">
          <label class="text-sm font-medium">文章类型</label>
          <div class="flex gap-4">
            <label class="flex items-center gap-2">
              <input
                type="radio"
                :value="false"
                v-model="articleForm.type"
                class="w-4 h-4 border-primary text-primary focus:ring-primary"
              />
              <span>原创</span>
            </label>
            <label class="flex items-center gap-2">
              <input
                type="radio"
                :value="true"
                v-model="articleForm.type"
                class="w-4 h-4 border-primary text-primary focus:ring-primary"
              />
              <span>转载</span>
            </label>
          </div>
        </div>

        <!-- 转载链接 -->
        <div v-if="articleForm.type" class="space-y-2">
          <label class="text-sm font-medium">原文链接</label>
          <input
            v-model="articleForm.originalUrl"
            type="text"
            placeholder="请输入原文链接"
            class="w-full px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
          />
        </div>

        <!-- 文章封面 -->
        <div class="space-y-2">
          <label class="text-sm font-medium">文章封面</label>
          <div class="space-y-4">
            <!-- 封面预览 -->
            <div v-if="articleForm.articleCover" class="relative w-full max-w-md aspect-video">
              <img
                :src="articleForm.articleCover"
                alt="文章封面"
                class="w-full h-full object-cover rounded-md"
              />
              <button
                @click="removeCover"
                class="absolute top-2 right-2 p-1 rounded-full bg-red-500 text-white hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="h-4 w-4"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fill-rule="evenodd"
                    d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                    clip-rule="evenodd"
                  />
                </svg>
              </button>
            </div>

            <div class="flex gap-4">
              <!-- 隐藏的文件输入框 -->
              <input
                ref="fileInput"
                type="file"
                accept="image/*"
                class="hidden"
                @change="handleFileUpload"
              />

              <!-- 上传按钮 -->
              <button
                @click="triggerFileInput"
                :disabled="uploadLoading"
                class="px-4 py-2 rounded-md bg-secondary text-secondary-foreground hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50 flex items-center gap-2"
              >
                <svg
                  v-if="uploadLoading"
                  class="animate-spin h-4 w-4"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    class="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    stroke-width="4"
                  ></circle>
                  <path
                    class="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  ></path>
                </svg>
                {{ uploadLoading ? '上传中...' : '上传图片' }}
              </button>

              <!-- 输入链接 -->
              <input
                v-model="articleForm.articleCover"
                type="text"
                placeholder="或者直接输入图片链接"
                class="flex-1 px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              />
            </div>
          </div>
        </div>

        <!-- 文章简介 -->
        <div class="space-y-2">
          <label class="text-sm font-medium">文章简介</label>
          <textarea
            v-model="articleForm.articleIntroduction"
            rows="3"
            placeholder="请输入文章简介"
            class="w-full px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none"
          />
        </div>

        <!-- Markdown编辑器 -->
        <div class="space-y-2">
          <div class="flex justify-between items-center">
            <label class="text-sm font-medium">文章内容</label>
            <!-- 添加文件上传按钮 -->
            <div class="flex items-center gap-2">
              <input
                type="file"
                ref="mdFileInput"
                accept=".md,.markdown"
                class="hidden"
                @change="handleMdFileUpload"
              />
              <button
                @click="triggerMdFileInput"
                class="px-3 py-1 text-sm rounded-md bg-secondary text-secondary-foreground hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-ring"
              >
                导入 Markdown
              </button>
            </div>
          </div>
          <MdEditor
            v-model="articleForm.articleContent"
            language="zh-CN"
            :height="500"
            @onUploadImg="handleUploadImage"
          />
        </div>

        <!-- 发布设置 -->
        <div class="space-y-2">
          <label class="text-sm font-medium">发布设置</label>
          <div class="flex gap-4">
            <label class="flex items-center gap-2">
              <input
                type="radio"
                :value="false"
                v-model="articleForm.status"
                class="w-4 h-4 border-primary text-primary focus:ring-primary"
              />
              <span>公开</span>
            </label>
            <label class="flex items-center gap-2">
              <input
                type="radio"
                :value="true"
                v-model="articleForm.status"
                class="w-4 h-4 border-primary text-primary focus:ring-primary"
              />
              <span>私密</span>
            </label>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="flex justify-end">
          <button
            @click="handleSubmit"
            :disabled="loading"
            class="px-4 py-2 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
          >
            {{ loading ? '提交中...' : isEdit ? '更新文章' : '发布文章' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { articleApi } from '@/api/article'
import { uploadApi } from '@/api/upload'
import type { ArticleVO, CategoryVO } from '@/types'
import { useToast } from '@/components/ui/toast'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

const route = useRoute()
const router = useRouter()
const toast = useToast()

// 表单数据
const articleForm = ref({
  id: undefined as number | undefined,
  articleTitle: '',
  articleContent: '',
  articleIntroduction: '',
  articleCover: '',
  categoryId: 0,
  type: false, // false:原创 true:转载
  status: false, // false:公开 true:私密
  originalUrl: '',
})

const categories = ref<CategoryVO[]>([])
const loading = ref(false)
const isEdit = ref(false)
const uploadLoading = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)
const mdFileInput = ref<HTMLInputElement | null>(null)

// 处理图片上传
const handleUploadImage = async (files: File[], callback: (urls: string[]) => void) => {
  try {
    const urls = []
    for (const file of files) {
      const validation = uploadApi.validateImage(file)
      if (!validation.valid) {
        toast.error(validation.message!)
        continue
      }

      const res = await uploadApi.uploadFile(file)
      if (res.data.code === 200) {
        urls.push(res.data.data.fileUrl)
      }
    }
    callback(urls)
  } catch (err) {
    toast.error('图片上传失败')
  }
}

// 处理封面图片上传
const handleFileUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]

  if (!file) return

  const validation = uploadApi.validateImage(file)
  if (!validation.valid) {
    toast.error(validation.message!)
    return
  }

  uploadLoading.value = true
  try {
    const res = await uploadApi.uploadFile(file)
    if (res.data.code === 200) {
      articleForm.value.articleCover = res.data.data.fileUrl
      toast.success('上传成功')
    } else {
      toast.error('上传失败：' + res.data.msg)
    }
  } catch (err) {
    toast.error('上传失败')
  } finally {
    uploadLoading.value = false
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
}

// 移除封面图
const removeCover = () => {
  articleForm.value.articleCover = ''
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 触发文件选择
const triggerMdFileInput = () => {
  mdFileInput.value?.click()
}

// 处理 Markdown 文件上传
const handleMdFileUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]

  if (!file) return

  // 验证文件类型
  if (!file.name.match(/\.(md|markdown)$/i)) {
    toast.error('请上传 Markdown 文件')
    return
  }

  try {
    const reader = new FileReader()
    reader.onload = (e) => {
      const content = e.target?.result as string
      if (content) {
        // 如果编辑器已有内容，提示用户
        if (articleForm.value.articleContent.trim()) {
          if (confirm('编辑器中已有内容，是否替换？')) {
            articleForm.value.articleContent = content
          }
        } else {
          articleForm.value.articleContent = content
        }
        toast.success('文件导入成功')
      }
    }
    reader.onerror = () => {
      toast.error('文件读取失败')
    }
    reader.readAsText(file)
  } catch (err) {
    toast.error('文件处理失败')
  } finally {
    // 清空文件输入，允许重复上传同一文件
    if (input) {
      input.value = ''
    }
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await articleApi.getCategories()
    if (res.code === 200) {
      categories.value = res.data
    } else {
      toast.error('加载分类失败：' + res.msg)
    }
  } catch (err) {
    toast.error('加载分类失败')
  }
}

// 加载文章详情
const loadArticle = async (id: number) => {
  loading.value = true
  try {
    const res = await articleApi.getArticleById(id)
    if (res.code === 200) {
      const article = res.data
      articleForm.value = {
        id: article.id,
        articleTitle: article.articleTitle,
        articleContent: article.articleContent,
        articleIntroduction: article.articleIntroduction || '',
        articleCover: article.articleCover || '',
        categoryId: article.categoryId,
        type: article.type,
        status: article.status,
        originalUrl: article.originalUrl || '',
      }
    } else {
      toast.error('加载文章失败：' + res.msg)
    }
  } catch (err) {
    toast.error('加载文章失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!articleForm.value.articleTitle.trim()) {
    toast.warning('请输入文章标题')
    return
  }
  if (!articleForm.value.articleContent.trim()) {
    toast.warning('请输入文章内容')
    return
  }
  if (!articleForm.value.categoryId) {
    toast.warning('请选择文章分类')
    return
  }

  loading.value = true
  try {
    const res = await articleApi.createOrUpdate(articleForm.value)
    if (res.code === 200) {
      toast.success(isEdit.value ? '更新文章成功' : '发布文章成功')
      router.push('/articles')
    } else {
      toast.error((isEdit.value ? '更新' : '发布') + '文章失败：' + res.msg)
    }
  } catch (err) {
    toast.error((isEdit.value ? '更新' : '发布') + '文章失败')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await loadCategories()

  const articleId = route.query.id
  if (articleId) {
    isEdit.value = true
    await loadArticle(Number(articleId))
  }
})
</script>
